<?php

namespace App\Http\Model;

use App\Http\Model\Api\FinanceWallet;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class User extends Base
{
    protected $table = 'share_user';
    protected $userTable = 'user';
    protected $connection = 'mysql_kkaudio';


    //用户缓存键
    private $redis_cache_user_key = 'CACHE:USER:'; //CACHE:USER:{user_id}
    //sql查询键
    private $sql_user_fields = [
        'user.user_id as user_id', 'user.mobile_phone as phone',
        'user.uuid as user_uid', 'user.nickname as nickname',
        'user.birthday as birthday', 'user.affective_state as affective_state', 'user.gender as gender',
        'user.sign as sign', 'user.province as province', 'user.occupation as occupation',
        'user.school as school', 'user.province as province', 'user.city as city', 'user.portrait as portrait', 'user.active_certify as active_certify', 'user.code as code', 'user.guid as guid', 'user.channel_id as channel_id',
        'user.liang as liang',
        'user.super as super',
        'user.official as official',
        'user.waiter as waiter',
        'user.create_timestamp as create_timestamp',
        'user.invite_uid as invite_uid',
        'user.v as v',
        'user.v_desc as v_desc',
        'user.voice_sign_url as voice_sign_url',
        'user.voice_sign_time as voice_sign_time',
        'user.label_ids as label_ids',
        'user.is_open_code as is_open_code',
        'user.is_visitor as is_visitor',
    ];

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /*
     * 添加用户关系
     * @param [$u_id]   新用户id
     * @param [$invite_uid]   邀请用户id
     * */
    public function createUserInvate($user_id, $invite_uid)
    {
        $data['user_id'] = $user_id;//新用户id
        $data['invite_uid'] = $invite_uid;//邀请人id
        $data['created_at'] = $data['updated_at'] = date_ymd();
        $res = DB::table($this->table)->insert($data);
        if (!$res)
            return false;
        return $res;
    }

    //查看用户邀请者
    public function showUserInvite($user_id)
    {
        $one_level_user = DB::table("share_user")->where(['user_id' => $user_id])->first();
        if (!$one_level_user)
            return false;
        $one_level_user = self::objToArray($one_level_user);
        $data[1] = $one_level_user;

        $two_level_user = DB::table("share_user")->where(['user_id' => $one_level_user['invite_uid']])->first();
        if ($two_level_user) {
            $two_level_user = self::objToArray($two_level_user);

            $data[2] = $two_level_user;
        }
        return $data;
    }

    /*
         * api接口
         * @param [$user_id]   查询用户
         * @param [$checkTime]   验证时间 单位（天）
         * */
    public function showUserRegisterTime($user_id)
    {
        $user = DB::table("share_user")->where(['user_id' => $user_id])->first();
        return self::objToArray($user);
    }

    /*
         * 我的邀请用户信息
         * @param [$user_id]   用户id
         * */
    public function getMyInviteUser($user_id)
    {
        $data = DB::table($this->table)->where(['invite_uid' => $user_id])->get();
        return self::objToArray($data);
    }

    /*
         * 获取邀请多用户信息
         * @param [$invite_user_ids]   用户id 合集
         * */
    public function getInviteUsers($invite_user_ids)
    {
        $data = DB::connection("mysql_kkaudio")
            ->table("user")
            ->whereIn('user_id', $invite_user_ids)
            ->select(['uuid', 'create_time', 'nickname'])->get();
        return self::objToArray($data);
    }


    /*
      * 获取邀请用户信息
      * @param [$uuid]   用户id
      * */
    public function getInviteUserInfo($user_id)
    {
        $data = DB::connection("mysql_kkaudio")
            ->table("user")
            ->where('user_id', $user_id)
            ->select(['user_id', 'uuid'])->first();
        return self::objToArray($data);
    }


    /*
      * 获取主库用户信息
      * @param [$uuid]   用户id
      * */
    public function getUserInfoByKkaudio($user_id)
    {
        $data = DB::connection("mysql_kkaudio")
            ->table("user")
            ->where('user.user_id', $user_id)
            ->leftJoin('finance_wallet', 'finance_wallet.user_id', '=', 'user.user_id')
            ->first();
        $head_img = json_decode($data->portrait, true);

        if (!empty($head_img)) {
            if (strpos($head_img[0], 'http:') !== false) {
                $data->head_img = $head_img[0];
            } elseif (strpos($head_img[0], 'qqapp') !== false) {
                $data->head_img = $head_img[0];
            }
            {
                $data->head_img = "http://ztaudio-res.whzcth.com" . $head_img[0];
                // $data->head_img = "https://ztaudio-res.qianyancm.com" . $head_img[0];
            }
        }
        return self::objToArray($data);
    }

    /**
     * 获取对应用户ID数据
     * @param $id_arr
     * @return array
     */
    public function get_users_by_ids($id_arr)
    {
        if (empty($id_arr)) {
            return [];
        }

        $user_in_cache = Redis::MGET(array_map(function ($user_id) {
            return $this->redis_cache_user_key . $user_id;
        }, $id_arr));

        $user_in_cache = array_map(function ($user) {
            $user = json_decode($user, true);
            return $user;
        }, array_filter($user_in_cache));

//        foreach ($user_in_cache as &$cache_val) {
        //查看用户头像审核是否通过
//            $cache_val = $this->checkImgChange($cache_val, $cache_val['user_id'], $cur_user_id);
//        }
        $user_in_cache = [];

        $result = [];
        if (!empty($user_not_in_cache = array_diff_key($id_arr, $user_in_cache))) {
            // 查询未命中缓存用户
            $users = DB::connection("mysql_kkaudio")->table("user")->whereIn("user_id", $user_not_in_cache)
                ->get($this->sql_user_fields);
            $result = self::objToArray($users);

            foreach ($result as $key => $value) {
                $result[$key]['images'] = $this->build_images($value['portrait']);
                $result[$key]['thumbnails'] = $this->build_thumbnails($value['portrait']);

                $this->set_cache_user(intval($value['user_id']), $result[$key]);

                //查看用户头像审核是否通过
//                $result[$key] = $this->checkImgChange($result[$key], $value['user_id'], $cur_user_id);
            }
        }
        return array_merge($user_in_cache, $result);
    }

    /**
     * 设置用户缓存
     * @param $user_id
     * @param $user_item
     * @param $expire_time
     * @return bool
     */
    private function set_cache_user($user_id, $user_item, $expire_time = 3600)
    {
        $key = $this->redis_cache_user_key . $user_id;
        Redis::SET($key, json_encode($user_item), 'EX', $expire_time);
        return true;
    }

    /**
     * 生成缩略图
     * @param $portrait_json
     * @return array
     */
    public function build_thumbnails($portrait_json)
    {
        $portrait = json_decode($portrait_json, true);
        $images = [];
        if ($portrait) {
            foreach ($portrait as $k => $v) {
                if (strtolower(substr($v, 0, 4)) == "http") {
                    $images[$k] = $v;
                } else {
                    $arr = pathinfo($v);
                    $images[$k] = env('APP_PIC_DOMAIN') . $v . '?x-oss-process=style/thumbnails';
                    // $images[$k] = env('APP_PIC_DOMAIN') . $v . '!thumbnails.jpg';
                    if (isset($arr['extension']) && strtolower($arr['extension']) == 'gif') {
                        $images[$k] = env('APP_PIC_DOMAIN') . $v;
                    }
                }

            }
        }
        return $images;
    }

    /**
     * 添加图片url列表
     * @param $portrait_json
     * @return array
     */
    public function build_images($portrait_json)
    {
        $portrait = json_decode($portrait_json, true);
        $images = [];
        if ($portrait) {
            foreach ($portrait as $k => $v) {
                if (strtolower(substr($v, 0, 4)) == "http") {
                    $images[$k] = $v;
                } else {
                    $images[$k] = env('APP_PIC_DOMAIN') . $v;
                    // $images[$k] = env('APP_PIC_DOMAIN') . $v . '!thumbnails.jpg';
                }

            }
        }
        return $images;
    }

    public function getUserDiamondByKkaudio($user_id)
    {
        $data = DB::connection("mysql_kkaudio")
            ->table("finance_wallet")
            ->where('user_id', $user_id)
            ->first();
        return self::objToArray($data);
    }

    /*
     * 获取邀请用户信息
     * @param [$uuid]   用户id
     * */
    public function getUserInfoByApi($user_id)
    {
        $data = DB::connection($this->connection)
            ->table($this->userTable)
            ->where('user_id', $user_id)
            ->select(['user_id', 'uuid', 'nickname', 'portrait', 'mobile_phone'])->first();
        $data = self::objToArray($data);
        $data['portrait'] = build_image(json_decode($data['portrait'])[0]);
//        $data['username'] = '';
        return $data;
    }

    public function getUserFinance($user_id)
    {
        $where['user_id'] = $user_id;
        $data = DB::connection($this->connection)
            ->table('finance_wallet')
            ->where('user_id', $user_id)
            ->select('user_id', 'diamond_balance')->first();
        $data = self::objToArray($data);
        return $data;
    }

    public function getUserInfoToCache($user_id)
    {
        $key = "USER:INFO:CACHE" . ':' . $user_id;
        $cache = Redis::GET($key);
        if (!$cache) {
            $data = DB::connection($this->connection)
                ->table($this->userTable)
                ->where('user_id', $user_id)
                ->select(['user_id', 'uuid', 'nickname', 'portrait', 'mobile_phone', 'code'])->first();
            $data = self::objToArray($data);
            $data['portrait'] = build_image(json_decode($data['portrait'])[0]);
            Redis::SET($key, json_encode($data), 'EX', 120);
            $cache = Redis::GET($key);
        }
        return json_decode($cache, true);
    }

    //查询实名认证用户 是否为活动期间内邀请注册
    public function checkInviteUser($user_id, $date)
    {
        $create_time[] = date('Y-m-d 00:00:00');
        $create_time[] = date('Y-m-d 23:59:59');
        $date = explode(' - ', $date);
        $register_time[] = strtotime($date[0]);
        $register_time[] = strtotime($date[1]);
        $data = DB::connection($this->connection)
            ->table('user_convene')
            ->leftJoin('user_verify', 'user_verify.user_id', '=', 'user_convene.user_id')
            ->where('invite_user_id', $user_id)
            ->where('result_code', '1000')
            ->where('user_convene.state', '1')
            ->whereBetween('user_convene.created_at', $register_time)
            ->whereBetween('user_verify.create_time', $create_time)
            ->get(['user_convene.user_id']);
        return self::objToArray($data);
    }


    //查询实名认证用户 是否为活动期间内邀请注册
    public function checkInviteUserList($user_id, $date)
    {
        $date = explode(' - ', $date);
        $register_time[] = strtotime($date[0]);
        $register_time[] = strtotime($date[1]);
        $data = DB::connection($this->connection)
            ->table('user_convene')
            ->leftJoin('user_verify', 'user_verify.user_id', '=', 'user_convene.user_id')
            ->where('invite_user_id', $user_id)
            ->where('result_code', '1000')
            ->where('user_convene.state', '1')
            ->whereBetween('user_convene.created_at', $register_time)
            ->whereBetween('user_verify.create_timestamp', $register_time)
            ->get(['user_convene.user_id']);
        return self::objToArray($data);
    }

    //关注用户
    public function followUser($user_id, $start_time)
    {
        $change_time[] = $start_time;
        $change_time[] = strtotime(date('Y-m-d 23:59:59'));
        $data = DB::connection($this->connection)
            ->table('friends_follow')
            ->where('user_id', $user_id)
            ->whereBetween('create_timestamp', $change_time)
            ->get();
        return self::objToArray($data);
    }

    //用户动态
    public function getUserTrendsContent($user_id, $start_time)
    {
        $change_time[] = $start_time;
        $change_time[] = strtotime(date('Y-m-d 23:59:59'));
        $data = DB::connection($this->connection)
            ->table('trends_content')
            ->where('user_id', $user_id)
            ->where('state', 1)
            ->whereBetween('create_timestamp', $change_time)
            ->get();
        return self::objToArray($data);
    }

    //查询用户订单
    public function getUserRechargeOrder($user_id, $start_time)
    {
        $create_time[] = date('Y-m-d H:i:s', $start_time);
        $create_time[] = date('Y-m-d 23:59:59');
        $data = DB::connection($this->connection)
            ->table('finance_recharge_order')
            ->whereBetween('update_time', $create_time)
            ->where(['user_id' => $user_id, 'status' => 1, 'price' => 100])
            ->get();
        return self::objToArray($data);
    }

    //用户砸蛋
    public function getUserHammerLog($user_id, $start_time)
    {
        $change_time[] = $start_time;
        $change_time[] = strtotime(date('Y-m-d 23:59:59'));
        $data = DB::connection($this->connection)
            ->table('throwing_hammer_log')
            ->where('user_id', $user_id)
            ->where('change', '<', 0)
            ->whereBetween('create_timestamp', $change_time)
            ->sum('change');
        return self::objToArray($data);
    }
}
